package cn.datawin.service;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.springframework.stereotype.Service;
import com.mongodb.BasicDBObject;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import cn.datawin.bean.page.ReqData;
import cn.datawin.bean.page.RespData;
import cn.datawin.util.DbUtil;
import cn.datawin.util.JDBCUtil;
import cn.datawin.util.MD5;

@Service
public class DataService extends BaseService {

	public RespData<List<DBObject>> getTestdata(String col,ReqData reqData){
		return makeRes(col,reqData);
		
	}
	
	public RespData<List<DBObject>> makeRes(String col,ReqData reqData){
		RespData<List<DBObject>> respData = new RespData<List<DBObject>>();
		//获取条件
		int start = (reqData.getPage() - 1) * reqData.getRows();
		BasicDBObject sort = null;
		//设置sort
		if(reqData.getSort()!=null){
			sort = new BasicDBObject(reqData.getSort(), sortmap.get(reqData.getOrder())); 
		}
		long count=1000;
		//super.findList(col, query, sort, start, reqData.getRows())
		DBCollection db=DbUtil.getcoll(col);
		if(db.count()<1000) count=db.count();
		DBCursor dbc=db.find().skip(start).limit(reqData.getRows());
		ArrayList<DBObject> list = new ArrayList<DBObject>();
		if (dbc != null) {
			while (dbc.hasNext()) {
				DBObject dbo = dbc.next();
				if(dbo.get("_id")!=null){
					dbo.put("_id", dbo.get("_id").toString());
				}
				list.add(dbo);
			}
		}
		respData.setRows(list);
		respData.setTotal(count);
		return respData;
	}
	public List<String> getDataNames(){
		List<String> names=new ArrayList<String>();
		for (String tmp : DbUtil.getcolls()) {
			if(tmp.startsWith("b_")||tmp.startsWith("c_")){
				names.add(tmp);
			}
		}
		return names;
	}
	
	public RespData<List<Map<String, Object>>> findurls(String url){
		/*
		 *  select * from xxx limit 10 offset 0;
			offset 偏移量 0表示从第一条开始
			limit 共取几条 10表示本次查询10条
		 * */
		try {
			Object obj = JDBCUtil.QueryObject("select count(1) from url");
			int count=Integer.parseInt(obj.toString());
			RespData<List<Map<String, Object>>> respData = new RespData<List<Map<String, Object>>>();
			if(null!=url && !"".equals(url)){
				long id = MD5.md5_long(url);
				List<Map<String, Object>> objects=JDBCUtil.QueryObjects("select id, href from url where id=? limit 100", id);
				respData.setRows(objects);
				respData.setTotal(count);
				return respData;
			}else{
				List<Map<String, Object>> objects=JDBCUtil.QueryObjects("select id, href from url limit 100");
				respData.setRows(objects);
				respData.setTotal(count);
				return respData;
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return null;
	}
}
